package com.example.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bean.Books;
import com.example.bean.Borrow;
import com.example.bean.ScoreData;
import com.example.exception.ServiceException;
import com.example.mapper.BorrowMapper;
import com.example.mapper.ScoreDataMapper;
import com.example.service.BooksService;
import com.example.mapper.BooksMapper;
import com.example.until.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author wjf
* @description 针对表【books】的数据库操作Service实现
* @createDate 2022-10-11 18:27:22
*/
@Service
@Slf4j
public class BooksServiceImpl extends ServiceImpl<BooksMapper, Books> implements BooksService{

    @Resource
    private BooksMapper booksMapper;

    @Resource
    private BorrowMapper borrowMapper;

    @Resource
    private ScoreDataMapper scoreDataMapper;

    @Transactional
    @Override
    public IPage<Books> findPage(IPage<Books> page, String name, String author) {
        try {
            IPage<Books>  books = booksMapper.findPage(page,name,author);
            List<Books> records = books.getRecords();
            for (Books book:records){
                LambdaQueryWrapper<ScoreData> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ScoreData::getBookId, book.getId());
                List<ScoreData> scoreData = scoreDataMapper.selectList(queryWrapper);
                if (scoreData!=null){
                    //过滤查出该书的所有分数
                    List<Integer> collect = scoreData.stream().map(m -> m.getScore()).collect(Collectors.toList());
                    DoubleSummaryStatistics doubleSummaryStatistics = collect.stream().mapToDouble((s) -> s).summaryStatistics();
                    double average = doubleSummaryStatistics.getAverage();  //平均分
                    //设置平均分
                    book.setScore(average);
                    //同步更新到book表
                    booksMapper.updateById(book);
                }
            }
            return books;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(ResultCodeEnum.SERVICE_ERROR);
        }
    }

    @Transactional
    @Override
    public Boolean findAndSaveBook(Integer bookId, Integer userId) {
        LambdaQueryWrapper<Borrow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Borrow::getBookId,bookId)
                .eq(Borrow::getUserId,userId);
        Borrow one = borrowMapper.selectOne(queryWrapper);  //根据userId和bookId查数据库
        if (one==null){      //为空 存数据
            Borrow borrow = new Borrow();
            borrow.setBorrowId(genOrder(bookId,userId));  //设置借阅号
            borrow.setUserId(userId);
            borrow.setBookId(bookId);
            borrow.setBorrowTime(DateUtil.now());
            int insert = borrowMapper.insert(borrow);
            if (insert==1){
                // 借阅信息存好后 更改books库存
                Books books1 = booksMapper.selectById(bookId);
                Integer num = books1.getNum();
                Books books = new Books();
                books.setNum(num-1);
                books.setId(bookId);
                int i = booksMapper.updateById(books);
                if (i==1){
                    return true;
                }else {
                    throw new ServiceException(ResultCodeEnum.NUM); //217 该书籍被借完
                }
            }else {
                throw new ServiceException(ResultCodeEnum.SERVICE_ERROR); //201服务器异常
            }
        }else {
            if (one.getStatus()==0){
                throw new ServiceException(ResultCodeEnum.PROCESS);  //202 申请已提交 等待审核
            }else {
                throw new ServiceException(ResultCodeEnum.BORROW); //203 已借该书籍 勿重复提交
            }
        }
    }

    /**
     * 获取借阅号
     * @param bookId
     * @param userId
     * @return
     */
    public String genOrder(Integer bookId,Integer userId){
        String uuid = IdUtil.fastSimpleUUID();
        return userId+uuid+bookId;
    }
}




